<!-- 企业编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="640"
    :model-value="modelValue"
    :title="isUpdate ? '修改企业' : '新建企业'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="16">
        <el-col :sm="24" :xs="24">
          <el-form-item label="企业名称" prop="company_name">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.company_name"
              placeholder="请输入企业名称"
            />
          </el-form-item>

          <el-form-item label="企业分类" prop="category_id">
            <el-select
              clearable
              v-model="form.category_id"
              placeholder="请选择分类"
              class="ele-fluid"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
                {{ item.title }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="站点2" prop="site_id">
            <el-select
              clearable
              v-model="form.site_id"
              placeholder="请选择站点"
              class="ele-fluid"
            >
              <el-option
                v-for="item in siteList"
                :key="item.id"
                :label="item.region_name"
                :value="item.site_id"
              >
                {{ item.region_name }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="!isUpdate" label="联系人" prop="contacts">
            <el-input clearable :maxlength="20" v-model="form.contacts" />
          </el-form-item>
          <el-form-item v-if="!isUpdate" label="联系电话" prop="contacts_tel">
            <el-input clearable :maxlength="20" v-model="form.contacts_tel" />
          </el-form-item>
          <el-form-item label="备注" prop="introduction">
            <el-input clearable v-model="form.introduction" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import { addCompany, updateCompany, getCompanyCates } from '@/api/company';
  import { getMyCityList } from '@/api/system/region';

  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 部门列表 */
  const siteList = ref([]);

  /** 部门列表 */
  const cateList = ref([]);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    company_name: '',
    contacts: '',
    contacts_tel: '',
    site_id: void 0,
    category_id: void 0,
    introduction: ''
  });

  /** 表单验证规则 */
  const rules = reactive({
    company_name: [
      {
        required: true,
        message: '请输入企业名称',
        type: 'string',
        trigger: 'blur'
      }
    ],

    site_id: [
      {
        required: true,
        message: '请选择站点',
        type: 'int',
        trigger: 'blur'
      }
    ],

    category_id: [
      {
        required: true,
        message: '请选择分类',
        type: 'int',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      const saveOrUpdate = isUpdate.value ? updateCompany : addCompany;
      saveOrUpdate(form)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  /** 获取角色数据 */
  const getSiteList = () => {
    getMyCityList({})
      .then((res) => {
        siteList.value = res;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  /** 获取角色数据 */
  const getCates = () => {
    getCompanyCates({})
      .then((res) => {
        cateList.value = res.list;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        getCates();
        getSiteList();
        if (props.data) {
          assignFields({
            ...props.data,
            password: ''
          });
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
